import { useEffect, useRef, useState } from "react"
import style from './style.module.css'
import { Button, Form, Input } from "antd"
function Chat() {
    const divRef = useRef()
    const wsRef = useRef(null)
    const [arr, setArr] = useState([])
    let user_id = 'me'
    const [form] = Form.useForm()
    const ws = () => {
        wsRef.current = new WebSocket(`ws://81.70.224.2:8003/koa/ws?user_id=${user_id}&server_id=300`)
        wsRef.current.onopen = () => {
            console.log('连接成功');
            wsRef.current.send(JSON.stringify({ "type": "getChatList" }))
        }
        wsRef.current.onmessage = (res) => {
            const data = JSON.parse(res.data)
            if (data.type === 'getChatList') {
                setArr(data.data)
                setTimeout(() => {
                    divRef.current.scrollTop = 999999
                    form.resetFields()
                }, 1)
            } else if (data.type === 'addMessage') {
                wsRef.current.send(JSON.stringify({ "type": "getChatList" }))
            }
        }
    }
    useEffect(() => {
        ws()
    }, [])
    const onFinish = (value) => {
        if (!value.text) {
            alert('请输入')
            return
        }
        wsRef.current.send(JSON.stringify({ type: "addMessage", data: { message: value.text, type: 'text' } }))
    }
    console.log(arr);

    return (
        <div>
            <div className={style.box}>
                <div className={style.main} ref={divRef}>
                    {
                        arr.map((item) => {
                            return (
                                <div className={user_id ? style.list1 : style.list2}>
                                    <img src={user_id ? item.user_avatar : item.other_avatar} alt="" />
                                    <p>{item.message}</p>
                                </div>
                            )
                        })
                    }
                </div>
                <div>
                    <Form form={form} onFinish={onFinish} style={{ display: 'flex', justifyContent: 'end' }}>
                        <Form.Item name='text'>
                            <Input style={{ width: 1000 }} />
                        </Form.Item>
                        <Form.Item>
                            <Button htmlType='submit'>发送</Button>
                        </Form.Item>
                    </Form>
                </div>
            </div>
        </div>
    )
}

export default Chat
